package Server;

import Data.MassageData;
import Search.CheckDuplicate;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class CreatGroup {
    private String id;

    static String sql = "insert into chat_room_list(group_id,creater_id) values (?,?);";
    String url = "jdbc:mysql://127.0.0.1:3306/nox?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
    String user = "root";
    String password = "Mi20030610.";


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public CreatGroup(String id) {
        this.id = id;
    }

    public String creatgroup() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection Conn = DriverManager.getConnection(url, user, password);
        PreparedStatement operation=Conn.prepareStatement(sql);

        long newid=new GetId().nextId();
        String group_id=String.valueOf(newid);
        group_id=group_id.substring(group_id.length()-10);
        CheckDuplicate check=new CheckDuplicate();
        boolean is=check.check(group_id,2);
        while(!is)
        {
            newid=new GetId().nextId();
            group_id=String.valueOf(newid);
            group_id=group_id.substring(group_id.length()-10);
            is=check.check(group_id,2);
        }

        System.out.println(group_id);

        operation.setString(1,group_id);
        operation.setString(2,id);

        int k=operation.executeUpdate();
        operation.close();
        if(k>0)
        {
            String newsql="insert into group_identity_list (id,identity,group_id) VAlUES (?,1,?);";
            //把群主消息插入的数据库里面
            operation=null;
            operation=Conn.prepareStatement(newsql);
            operation.setString(1,id);
            operation.setString(2,group_id);

            int x=operation.executeUpdate();
            if(x<=0) group_id=null;
            operation.close();
            Conn.close();
        }
        else group_id=null;
        return group_id;
    }
}
